package com.acmedcare.framework.exchange.center.core.resolve;

import com.acmedcare.framework.kits.StringUtils;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicReference;

@SuppressWarnings("unused")
public class LocalFileResolve implements IPathResolve {

  private final String uri;

  private String name;

  private final String rootPath;

  public LocalFileResolve(String uri, String name, String rootPath) {
    this.uri = uri;
    this.name = name;
    this.rootPath = rootPath;
  }

  public LocalFileResolve(String uri, String rootPath) {

    this.uri = uri;
    this.rootPath = rootPath;
  }


  @Override
  public String resolve() throws Exception {

    AtomicReference<String> fileName = new AtomicReference<>(
        uri.substring(uri.lastIndexOf(File.separator)));
    if (StringUtils.isNotEmpty(name)) {
      fileName.set(name);
    }

    Path targetPath = Paths
        .get(rootPath + File.separator + fileName);

    Path orgPath = Paths.get(uri);
    if (!Files.exists(orgPath)) {

      throw new Exception("本地文件:" + uri + ",不存在无法完成文件复制！");
    }

    //不存在文件夹时直接创建文件夹
    if (!Files.exists(Paths.get(rootPath))) {
      Files.createDirectories(Paths.get(rootPath));
    }

    //如果目标位置存在文件则直接先删除文件
    if (Files.exists(targetPath)) {

      Files.delete(targetPath);
    }

    Files.copy(orgPath, targetPath);

    return targetPath.toString();
  }
}
